package com.wwinsoft.framework.service.security;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.wwinsoft.framework.entity.security.Authority;
import com.wwinsoft.framework.entity.security.Group;
import com.wwinsoft.framework.entity.security.User;
import com.wwinsoft.modules.security.springsecurity.SpringSecurityUser;

/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 *
 * @author calvin
 */
@Transactional(readOnly = true)
public class UserDetailsServiceImpl implements UserDetailsService {

    private AccountManager accountManager;

    /**
     * 获取用户Details信息的回调函数.
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        User user = accountManager.findUserByLoginName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户" + username + " 不存在");
        }

        Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(user);

        //-- report示例中无以下属性, 暂时全部设为true. --//
        boolean enabled = user.isEnabled();
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        SpringSecurityUser userdetails = new SpringSecurityUser(user.getUserId(), user
                .getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
        userdetails.setFirstName(user.getFirstName());
        return userdetails;
    }

    /**
     * 获得用户所有角色的权限集合.
     */
    private Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
        Set<GrantedAuthority> authSet = Sets.newHashSet();
        for (Group role : user.getGroupList()) {
            for (Authority authority : role.getAuthorityList()) {
                authSet.add(new GrantedAuthorityImpl(authority.getPrefixedName()));
            }
        }
        return authSet;
    }

    @Autowired
    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }
}
